// 本地存储工具类
class StorageService {
  constructor() {
    this.prefix = "pet_";
  }

  // 生成存储键名
  getKey(key) {
    return this.prefix + key;
  }

  // 设置数据
  set(key, data) {
    try {
      const storageKey = this.getKey(key);
      wx.setStorageSync(storageKey, data);
      return true;
    } catch (error) {
      console.error("存储数据失败:", error);
      return false;
    }
  }

  // 获取数据
  get(key, defaultValue = null) {
    try {
      const storageKey = this.getKey(key);
      const data = wx.getStorageSync(storageKey);
      return data !== "" ? data : defaultValue;
    } catch (error) {
      console.error("获取数据失败:", error);
      return defaultValue;
    }
  }

  // 删除数据
  remove(key) {
    try {
      const storageKey = this.getKey(key);
      wx.removeStorageSync(storageKey);
      return true;
    } catch (error) {
      console.error("删除数据失败:", error);
      return false;
    }
  }

  // 清空所有数据
  clear() {
    try {
      wx.clearStorageSync();
      return true;
    } catch (error) {
      console.error("清空数据失败:", error);
      return false;
    }
  }

  // 获取存储信息
  getInfo() {
    try {
      return wx.getStorageInfoSync();
    } catch (error) {
      console.error("获取存储信息失败:", error);
      return null;
    }
  }

  // 检查键是否存在
  has(key) {
    try {
      const storageKey = this.getKey(key);
      const data = wx.getStorageSync(storageKey);
      return data !== "";
    } catch (error) {
      return false;
    }
  }

  // 获取所有键
  keys() {
    try {
      const info = wx.getStorageInfoSync();
      return info.keys
        .filter((key) => key.startsWith(this.prefix))
        .map((key) => key.replace(this.prefix, ""));
    } catch (error) {
      console.error("获取键列表失败:", error);
      return [];
    }
  }

  // 用户相关存储
  user = {
    // 保存用户信息
    setUserInfo: (userInfo) => {
      return this.set("userInfo", userInfo);
    },

    // 获取用户信息
    getUserInfo: () => {
      return this.get("userInfo");
    },

    // 保存登录状态
    setLoginStatus: (status) => {
      return this.set("loginStatus", status);
    },

    // 获取登录状态
    getLoginStatus: () => {
      return this.get("loginStatus", false);
    },

    // 保存token
    setToken: (token) => {
      return this.set("token", token);
    },

    // 获取token
    getToken: () => {
      return this.get("token", "");
    },

    // 清除用户数据
    clearUserData: () => {
      this.remove("userInfo");
      this.remove("loginStatus");
      this.remove("token");
    },
  };

  // 帖子相关存储
  post = {
    // 保存帖子缓存
    setPostCache: (postId, postData) => {
      return this.set(`post_${postId}`, postData);
    },

    // 获取帖子缓存
    getPostCache: (postId) => {
      return this.get(`post_${postId}`);
    },

    // 保存帖子列表缓存
    setPostListCache: (key, posts) => {
      return this.set(`postList_${key}`, posts);
    },

    // 获取帖子列表缓存
    getPostListCache: (key) => {
      return this.get(`postList_${key}`, []);
    },

    // 保存点赞状态
    setLikeStatus: (postId, status) => {
      return this.set(`like_${postId}`, status);
    },

    // 获取点赞状态
    getLikeStatus: (postId) => {
      return this.get(`like_${postId}`, false);
    },

    // 清除帖子缓存
    clearPostCache: (postId) => {
      if (postId) {
        this.remove(`post_${postId}`);
        this.remove(`like_${postId}`);
      } else {
        // 清除所有帖子相关缓存
        const keys = this.keys();
        keys.forEach((key) => {
          if (key.startsWith("post_") || key.startsWith("like_")) {
            this.remove(key);
          }
        });
      }
    },
  };

  // 设置相关存储
  settings = {
    // 保存主题设置
    setTheme: (theme) => {
      return this.set("theme", theme);
    },

    // 获取主题设置
    getTheme: () => {
      return this.get("theme", "light");
    },

    // 保存通知设置
    setNotificationSettings: (settings) => {
      return this.set("notificationSettings", settings);
    },

    // 获取通知设置
    getNotificationSettings: () => {
      return this.get("notificationSettings", {
        like: true,
        comment: true,
        follow: true,
        system: true,
      });
    },

    // 保存搜索历史
    setSearchHistory: (history) => {
      return this.set("searchHistory", history);
    },

    // 获取搜索历史
    getSearchHistory: () => {
      return this.get("searchHistory", []);
    },

    // 添加搜索历史
    addSearchHistory: (keyword) => {
      const history = this.get("searchHistory", []);
      const newHistory = [
        keyword,
        ...history.filter((item) => item !== keyword),
      ].slice(0, 10);
      return this.set("searchHistory", newHistory);
    },

    // 清除搜索历史
    clearSearchHistory: () => {
      return this.remove("searchHistory");
    },
  };

  // 缓存相关存储
  cache = {
    // 设置缓存
    set: (key, data, expireTime = 3600000) => {
      // 默认1小时过期
      const cacheData = {
        data,
        expire: Date.now() + expireTime,
      };
      return this.set(`cache_${key}`, cacheData);
    },

    // 获取缓存
    get: (key) => {
      const cacheData = this.get(`cache_${key}`);
      if (!cacheData) return null;

      if (Date.now() > cacheData.expire) {
        this.remove(`cache_${key}`);
        return null;
      }

      return cacheData.data;
    },

    // 清除过期缓存
    clearExpired: () => {
      const keys = this.keys();
      keys.forEach((key) => {
        if (key.startsWith("cache_")) {
          const cacheData = this.get(key);
          if (cacheData && Date.now() > cacheData.expire) {
            this.remove(key);
          }
        }
      });
    },

    // 清除所有缓存
    clearAll: () => {
      const keys = this.keys();
      keys.forEach((key) => {
        if (key.startsWith("cache_")) {
          this.remove(key);
        }
      });
    },
  };
}

// 创建存储服务实例
const storageService = new StorageService();

export default storageService;
